package com.example.membership.service.impl;
import com.example.membership.dao.OrderDao;
import com.example.membership.dao.ProductDao;
import com.example.membership.dao.UserDao;
import com.example.membership.model.Order;
import com.example.membership.model.Product;
import com.example.membership.model.User;
import com.example.membership.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    private static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    private final OrderDao orderDao;
    private final UserDao userDao;
    private final ProductDao productDao;

    public OrderServiceImpl(OrderDao orderDao, UserDao userDao, ProductDao productDao) {
        this.orderDao = orderDao;
        this.userDao = userDao;
        this.productDao = productDao;
    }

    @Override
    @Transactional
    public void createOrder(Order order) {
        // 检查用户 ID 和商品 ID 是否有效
        if (order.getUserId() <= 0 || order.getProductId() <= 0) {
            throw new RuntimeException("用户 ID 或商品 ID 无效");
        }

        // 检查用户和商品是否存在
        User user = userDao.findById(order.getUserId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查商品是否存在
        Product product = productDao.findById(order.getProductId());
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }

        // 检查商品库存是否足够
        if (product.getStock() <= 0) {
            logger.error("商品已售罄，当前库存：{}", product.getStock());
            throw new RuntimeException("商品已售罄，当前库存：0");
        }

        // 检查商品库存是否足够
        if (product.getStock() < order.getQuantity()) {
            logger.error("商品库存不足，当前库存：{}，订单数量：{}", product.getStock(), order.getQuantity());
            throw new RuntimeException("商品库存不足，当前库存：" + product.getStock());
        }

        // 扣除用户积分
        int totalCost = product.getPrice() * order.getQuantity();
        if (user.getPoints() < totalCost) {
            throw new RuntimeException("积分不足，无法兑换商品");
        }

        // 更新用户积分
        user.setPoints(user.getPoints() - totalCost);
        userDao.update(user);

        // 更新商品库存和销量
        product.setStock(product.getStock() - order.getQuantity());
        product.setSales_count(product.getSales_count() + order.getQuantity());
        productDao.update(product);

        // 创建订单
        order.setStatus("已创建");
        orderDao.insert(order);
    }

    @Override
    public void updateOrder(Order order) {
        orderDao.update(order);
    }

    @Override
    public void deleteOrder(int id) {
        orderDao.delete(id);
    }

    @Override
    public List<Order> getAllOrders() {
        return orderDao.findAll();
    }

}